package org.scboy.dbms.service.imp;

import java.util.List;
import java.util.UUID;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.BaseDictionaryTypeJoinDao;
import org.scboy.dbms.service.DictionaryTypeJoinService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 字典业务类
 * @author yanghao
 *
 */
@Service
public class DictionaryTypeJoinServiceImpl implements DictionaryTypeJoinService {

	@Autowired
	EntityFactory factory;
	
	/**
	 * 分页查询字典
	 * @param model 查询参数
	 * @return 分页结果
	 */
	public Page page(Model model){
		BaseDictionaryTypeJoinDao dao=factory.getDao(BaseDictionaryTypeJoinDao.class);
		return dao.queryPage(model);
	}
	/**
	 * 查询列表
	 * @param model
	 * @return
	 */
	public List<Model> list(Model model){
		BaseDictionaryTypeJoinDao dao=factory.getDao(BaseDictionaryTypeJoinDao.class);
		List<Model> datas=dao.queryList(model);
		for (Model data : datas) {
			data.add("type", "Join");
		}
		return datas;
	}
	@Transactional
	public boolean add(String typeCode, String[] code) {
		BaseDictionaryTypeJoinDao dao=factory.getDao(BaseDictionaryTypeJoinDao.class);
		//删除掉原有的关联
		dao.delete(Model.create().add("typeCode", typeCode));
		//增加新的关联
		if(code!=null){
			for (String c : code) {
				Model roleUserType=new Model();
				roleUserType.add("id", UUID.randomUUID().toString());
				roleUserType.add("code", c);
				roleUserType.add("typeCode", typeCode);
				dao.insert(roleUserType);
			}
		}
		return true;
	}

	public boolean delete(String id) {
		BaseDictionaryTypeJoinDao dao=factory.getDao(BaseDictionaryTypeJoinDao.class);
		int result=dao.delete(Model.create().add("id", id));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}

	public String[] getCodes(String typeCode) {
		BaseDictionaryTypeJoinDao dao=factory.getDao(BaseDictionaryTypeJoinDao.class);
		List<Model> result=dao.select(Model.create().add("typeCode", typeCode));
		String [] codes=new String [result.size()];
		for (int i = 0; i < result.size(); i++) {
			codes[i]=result.get(i).getString("code");
		}
		return codes;
	}
}


